<?php

namespace App\Models\CacheModel\zl2;

use App\Models\Api\BaseCache;
use think\Log;
use traits\model\SoftDelete;
use AstroTool\Cache\CacheManage;

class Zl2TimeNote extends BaseCache
{
    use SoftDelete;

    protected $table = 'wechat_backup_07_18_14_43_00.zl2_time_note';

    protected $cacheModel = 'user.time_note';

    protected $deleteTime = 'delete_time';

    /**
     * 准时提醒 信息写入
     * @param int $uid
     * @param array $data
     * @return false|int
     */
    public function saveData(int $uid, array $data)
    {
        try
        {
            $id = $this->insertGetId($data);

            $this->listDataAdd($uid, [$id => $data['time']]);
        }
        catch (\Exception $e)
        {
            return false;
        }

        return (int)$id;
    }

    /**
     * 准时提醒数据更新
     * @param $id
     * @param array $data 更新数据
     * @return bool
     */
    public function updateData($id, $data)
    {
        try
        {
            $this->where('id', $id)->update($data);
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->setCache($data); // 更新详情缓存
        }
        catch (\Exception $e)
        {
            Log::write('准时提醒 更新错误：' . $e->getMessage() . "；错误文件「{$e->getFile()}」错误行数「{$e->getLine()}」");
            return false;
        }
        return true;
    }

    /**
     * 删除 准时提醒 记录
     * @param int $uid 用户ID
     * @param int $id 准时提醒 记录ID
     * @return bool
     */
    public function delData(int $uid, int $id): bool
    {
        try
        {
            self::destroy($id);
            $this->listDataDel($uid, [$id]); // 删除列表项
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->rmCache(); // 删除详情缓存
        }
        catch (\Exception $e)
        {
            Log::write('准时提醒 删除错误：' . $e->getMessage() . "；错误文件「{$e->getFile()}」错误行数「{$e->getLine()}」");
            return false;
        }
        return true;
    }

    /**
     * 批量获取 准时提醒 数据
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string|void
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {
                $this->where(['id' => ['in', $ids]]);
            } else
            {
                $this->where(['uid' => $type[0]]);
            }

            $data = $this->order("time {$sortType}")->column('uid,time,note,create_time,update_time,delete_time', 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        foreach ($resData as $orderId => $questionItemData)
        {
            $resData[$orderId] = arrayKeyData2int($questionItemData, ['uid', 'time', 'id', 'create_time', 'update_time']);
        }

        return $resData;
    }
}
